<template>
  <div class="container">
    <el-form :model="form" class="title" :rules="rules" ref="form">
      <div>
        <el-form-item class="account">
          <el-input v-model="form.searchValue" placeholder="企业名称/手机号码/邮箱"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="form.authStatus" placeholder="企业认证状态">
            <el-option label="等待认证" value="1"></el-option>
            <el-option label="审核通过" value="2"></el-option>
            <el-option label="审核不通过" value="3"></el-option>
            <el-option label="未认证" value="0"></el-option>
          </el-select>
        </el-form-item>
        <!-- <el-form-item>
          <el-select v-model="form.staffAuthStatus" placeholder="个人认证状态">
            <el-option label="等待认证" :value="1"></el-option>
            <el-option label="审核通过" :value="2"></el-option>
            <el-option label="审核不通过" :value="3"></el-option>
            <el-option label="未认证" :value="0"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item>
          <el-select v-model="form.socialSecurityAuthStatus" placeholder="社保认证状态">
            <el-option label="等待认证" value="1"></el-option>
            <el-option label="审核通过" value="2"></el-option>
            <el-option label="审核不通过" value="3"></el-option>
            <el-option label="未认证" value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label='创建时间' class="create_time">
          <el-date-picker v-model="form.startTime" value-format="yyyy-MM-dd" type="date" placeholder="开始时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label='至' class="create_time">
          <el-date-picker v-model="form.endTime" value-format="yyyy-MM-dd" type="date" placeholder="结束时间">
          </el-date-picker>
        </el-form-item>
      </div>
      <el-form-item class="btn_box">
        <el-button type="primary" @click="searchStatus">查询</el-button>
        <el-button type="primary" @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="auth_box">
      <el-button @click="allExamine('1')" type="info">认证企业</el-button>
      <!-- <el-button @click="allExamine('2')" type="info">认证个人</el-button> -->
      <el-button @click="allExamine('3')" type="info">认证社保登记</el-button>
      <el-button @click="freshTime()" type="info">刷新</el-button>
      <el-button @click="delFiles()" type="info">删除</el-button>
      <!-- <el-button @click="changeVisible" type="info">重置密码</el-button> -->
    </div>
    <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%" align="center"
      @selection-change="handleSelectionChange" :fit='true' v-loading='loading'>
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="name" label="公司名称" width="160" show-overflow-tooltip fixed></el-table-column>
      <el-table-column prop="contact" label="企业联系人姓名" width="160" show-overflow-tooltip></el-table-column>
      <el-table-column prop="contactPhone" label="企业联系人手机号码" width="160" show-overflow-tooltip></el-table-column>
      <el-table-column prop="contactMail" label="企业联系人邮箱" width="240" show-overflow-tooltip></el-table-column>
      <el-table-column label="企业认证状态" width="120">
        <template slot-scope="scope">
          <span class="auth_span">{{scope.row.authStatus | getName}}</span>
          <el-button type="text" @click="singleExamine('1',scope.row)">{{scope.row.authStatus!==2?'审核':'查看'}}
          </el-button>
        </template>
      </el-table-column>
      <!-- <el-table-column label="个人认证状态" width="120">
        <template slot-scope="scope">
          <span class="auth_span">{{scope.row.staffAuthStatus | getName}}</span>
          <el-button type="text" @click="singleExamine('2',scope.row)">{{scope.row.staffAuthStatus!==2?'审核':'查看'}}
          </el-button>
        </template>
      </el-table-column> -->
      <el-table-column label="社保认证" width="120">
        <template slot-scope="scope">
          <span class="auth_span">{{scope.row.socialSecurityAuthStatus | getName}}</span>
          <el-button type="text" @click="singleExamine('3',scope.row)">
            {{scope.row.socialSecurityAuthStatus!==2?'审核':'查看'}}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="160" show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.createTime }}</template>
      </el-table-column>
      <el-table-column label="刷新时间" width="160" show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.refreshTime }}</template>
      </el-table-column>
      <el-table-column prop="releaseJobNumber" label="发布职位数" width="100" show-overflow-tooltip></el-table-column>
      <el-table-column prop="natureText" label="单位性质" show-overflow-tooltip width="160">
        <template slot-scope="scope">
          <el-select v-model="scope.row.nature" @change="val=>{setNature(val,scope.row.id)}">
            <el-option v-for="item in nature" :label="item.name" :value="item.val" :key="item.val"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="industryText" label="所属产业" show-overflow-tooltip width="160">
        <template slot-scope="scope">
          <el-select v-model="scope.row.industry" @change="val=>{setIndustry(val,scope.row.id)}">
            <el-option v-for="item in industry" :label="item.name" :value="item.val" :key="item.val"></el-option>
          </el-select>
        </template>
      </el-table-column>
      <el-table-column prop="receiveResume" label="收到简历（查看/收到）" width="120" show-overflow-tooltip></el-table-column>
      <el-table-column label="首页推荐" width="120" show-overflow-tooltip>
        <template slot-scope="scope">{{ scope.row.homeRecommend?'是':'否' }}</template>
      </el-table-column>
      <el-table-column fixed="right" label="操作" width='220'>
        <template slot-scope="scope">
          <el-button @click="legalPerson(scope.row)" type="text" size="small">法人库信息</el-button>
          <el-button @click="handleClick(scope.row)" type="text" size="small">日志</el-button>
          <el-button type="text" size="small" @click="alterInfo(scope.row)">修改</el-button>
          <el-button type="text" size="small" @click="recommendOpen(scope.row)">{{scope.row.homeRecommend?'取消推荐':'推荐'}}
          </el-button>
          <!-- <el-button type="text" size="small">管理</el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <div class="page">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="form.page" :page-sizes="[10,30,60,100,200,300]" :page-size="form.size"
        layout="prev, pager, next, jumper, sizes, total" :total="total"></el-pagination>
    </div>
    <el-dialog :visible.sync="dialogVisible" width="40%" class="elDialog examine" :before-close="examineClose">
      <p slot="title" class="elDialog-header">
        <span>批量审核</span>
      </p>
      <el-form :model="examine" ref="examine" :rules="rules">
        <el-form-item label="审核结果：" prop="auditStatus">
          <el-radio-group v-model="examine.auditStatus">
            <el-radio :label="2">通过</el-radio>
            <el-radio :label="3">不通过</el-radio>
            <el-radio :label="1">待定</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核不通过原因：" v-if="examine.auditStatus===3" prop="auditCause">
          <el-input type="textarea" v-model="examine.auditCause"></el-input>
        </el-form-item>
        <!-- <el-form-item class="mid_box">
          <el-button @click="examineClose">取 消</el-button>
          <el-button type="primary" @click="onSubmit">确 定</el-button>
        </el-form-item> -->
      </el-form>
      <div slot="footer">
        <el-button @click="examineClose">取 消</el-button>
        <el-button type="primary" @click="onSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="recommendVisible" width="30%" :before-close="recommendClose" class="elDialog recommend">
      <p slot="title" class="elDialog-header">
        <span>首页推荐</span>
      </p>
      <el-form :model="recommendForm" ref="recommend" :rules="rules" label-width="100px">
        <el-form-item label="推荐排序：" prop="recommendOrder">
          <el-input v-model.number="recommendForm.recommendOrder"></el-input>
          <p>1～300整数，1为排序在前</p>
        </el-form-item>
        <el-form-item label="推荐截止时间：" prop="recommendEndTime">
          <el-date-picker v-model="recommendForm.recommendEndTime" type="date" placeholder="选择日期"
            :default-value='new Date()' :picker-options='options' value-format="yyyy-MM-dd HH:mm:ss"
            :disabled="recommendForm.alwaysRecommend">
          </el-date-picker>
          <el-checkbox v-model="recommendForm.alwaysRecommend" @change='resetRules'>始终推荐</el-checkbox>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="recommendClose">取 消</el-button>
        <el-button type="primary" @click="recommend">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getIndustry, getNature } from '../../../../api/index'
import { companyList, deletebatchcompany, companyAuthAll, companyStaffAuthAll, companySsAuthAll, freshtime, updateInfo, getOrder } from '../../../../api/enterprise';
import { encrypt } from '../../../../utils/unitFile'
import bus from '../../../common/bus'
export default {
  name: 'companyList',
  data () {
    var validateRecommendOrder = (rule, value, callback) => {
      console.log(value);

      if (value > 300 || value < 1) {
        callback(new Error('推荐顺序为1~300'));
      } else if (typeof value !== 'number') {
        callback(new Error('推荐顺序为数字'));
      } else {
        callback();
      }
    };
    return {
      loading: false,
      industry: [],
      nature: [],
      recommendVisible: false,
      dialogVisible: false,
      total: 0,
      id: '',
      // 验证弹窗表单
      examine: {
        authType: '',
        auditCause: '',
        auditStatus: '',
        companyIds: ''
      },
      choice: [],
      // 搜索条件
      form: {
        searchValue: '',
        socialSecurityAuthStatus: '',
        startTime: '',
        endTime: '',
        authStatus: '',
        size: 10,
        page: 1
      },
      // 推荐弹窗
      recommendForm: {
        recommendOrder: '',
        recommendEndTime: '',
        alwaysRecommend: false,
        homeRecommend: 1
      },
      tableData: [
        // {
        //   date: '2016-05-02',
        //   name: '王小虎',
        //   mail: 'wxd19890923@yahoo.com.cn(已验证)',
        //   phone: '12345678911(已验证)',
        //   address: '上海市普陀区金沙江路 1518 弄',
        //   zip: 200333,
        //   comp_auth: '认证未通过'
        // },
        // {
        //   date: '2016-05-04',
        //   name: '王小虎',
        //   province: '上海',
        //   phone: '12345678911',
        //   address: '上海市普陀区金沙江路 1517 弄',
        //   zip: 200333
        // },
        // {
        //   date: '2016-05-01',
        //   name: '王小虎',
        //   province: '上海',
        //   phone: '12345678911',
        //   address: '上海市普陀区金沙江路 1519 弄',
        //   zip: 200333
        // },
        // {
        //   date: '2016-05-03',
        //   name: '王小虎',
        //   province: '上海',
        //   phone: '12345678911',
        //   address: '上海市普陀区金沙江路 1516 弄',
        //   zip: 200333
        // }
      ],
      options: {
        disabledDate (time) {
          return time.getTime() < Date.now();
        }
      },
      rules: {
        auditStatus: [{ required: true, message: '请选择审核结果', trigger: 'change' }],
        recommendOrder: [{ required: true, message: '请输入推荐顺序', trigger: 'change' }, { validator: validateRecommendOrder }],
        recommendEndTime: [{ required: true, message: '请选择截止日期', trigger: 'change' }],
        auditCause: [
          { max: 100, message: '原因不能超过100个字' },
          { required: true, message: '请填写审核不通过原因', trigger: 'change' }
        ]
        // repassword: [{ required: true, message: '请输入确认密码', trigger: 'change' }, { validator: validateComfirmPwd }],
        // password: [
        //   { required: true, message: '请输入密码', trigger: 'blur' },
        //   { pattern: /^[0-9a-zA-Z_]{6,20}$/, message: '密码由长度为6-20的数字、字母或下划线组成' }
        // ]
      }
    };
  },
  created () {
    getNature().then(res => {
      if (res.success) {
        this.nature = res.data
      }
    });
    getIndustry().then(res => {
      if (res.success) {
        this.industry = res.data;
      }
    })
    this.form.authStatus = this.$route.query.authStatus || ''
    this.form.socialSecurityAuthStatus = this.$route.query.socialSecurityAuthStatus || ""
    this.getCompList();

  },
  watch: {
    // 根据路由改变来改变搜索内容
    '$route.fullPath': function (val, oldVal) {
      this.$nextTick(() => {
        this.form.authStatus = this.$route.query.authStatus || ""
        this.form.socialSecurityAuthStatus = this.$route.query.socialSecurityAuthStatus || ""
        if (this.$route.query.authStatus || this.$route.query.socialSecurityAuthStatus) {
          this.getCompList();
        }
      })
    }
  },
  filters: {
    // 获取认证状态
    getName (val) {
      switch (val) {
        case 1:
          return '等待认证';
        case 2:
          return '审核通过';
        case 3:
          return '审核未通过';
        default:
          return '未认证';
      }
    }
  },
  methods: {
    // 改变公司性质
    setNature (val, id) {
      updateInfo({ id, nature: val }).then(res => {
        if (!res.success) {
          this.$message.error(`${res.msg}`)
          this.getCompList()
        }
      })
    },
    // 改变公司产业
    setIndustry (val, id) {
      updateInfo({ id, industry: val }).then(res => {
        if (!res.success) {
          this.$message.error(`${res.msg}`)
          this.getCompList()
        }
      })
    },
    // 是否推荐
    recommendOpen (row) {
      if (row.homeRecommend) {
        updateInfo({ id: row.id, homeRecommend: 0 }).then(res => {
          if (res.success) {
            this.getCompList();
          } else {
            this.$message.error(`${res.msg}`)
          }
        })
      } else {
        getOrder(row.id).then(res => {
          if (res.success) {
            this.recommendForm.recommendOrder = res.data.recommendOrder || null
            this.recommendVisible = true;
            this.id = row.id;
          } else {
            this.$message.error(`${res.msg}`)
          }
        })
      }
    },
    // 推荐弹窗
    recommend () {
      this.$refs.recommend.validate(valid => {
        if (valid) {
          console.log(this.recommendForm);
          updateInfo({ ...this.recommendForm, id: this.id }).then(res => {
            console.log(res);
            if (res.success) {
              this.$message.success(`推荐成功`);
              this.getCompList();
            } else {
              this.$message.error(`${res.msg}`);
            }
            this.recommendClose()
          });
        }
      });
    },
    // 关闭推荐弹窗
    recommendClose () {
      this.$refs.recommend.resetFields();
      this.recommendVisible = false;
    },
    // 取消推荐时间验证
    resetRules (val) {
      console.log(val);

      this.recommendForm.alwaysRecommend = val;
      this.$refs.recommend.clearValidate('recommendEndTime');
      if (!val) {
        this.rules.recommendEndTime = [{ required: true, message: '请选择截止日期', trigger: 'change' }]
      } else {
        this.rules.recommendEndTime = []
      }
    },
    // 获取列表
    getCompList () {
      this.loading = true;
      let query = this.form;
      if (query.startTime) {
        query = { ...query, startTime: query.startTime + ' 00:00:00' };
      }
      if (query.endTime) {
        query = { ...query, endTime: query.endTime + ' 23:59:59' };
      }
      companyList(query).then(data => {
        if (data.success) {
          console.log(data);

          this.tableData = data.data.records;
          this.total = data.data.total;
          this.loading = false;
        } else {
          this.$message.error(`${data.msg}`);
          this.loading = false;
        }
      });
    },
    // 重置
    reset () {
      this.form.searchValue = '';
      this.form.socialSecurityAuthStatus = '';
      this.form.authStatus = '';
      this.form.startTime = '';
      this.form.endTime = '';
      this.form.page = 1;
      this.form.size = 10;
      this.getCompList();
    },
    handleSelectionChange (choice) {
      this.choice = choice;
    },
    // 企业认证
    allExamine (path) {
      if (this.choice.length < 1) {
        this.$message.error('请选择需要认证的公司!');
      } else {
        this.examine.authType = path;
        this.dialogVisible = true;
      }
    },
    // 删除公司
    delFiles () {
      if (this.choice.length < 1) {
        this.$message.error('请选择想要删除的公司!');
      } else {
        this.$confirm('您要删除企业，删除后不可恢复，是否确定操作？', '信息提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          callback: action => {
            console.log(action);
            if (action === 'confirm') {
              let formData = new FormData();
              formData.append('companyIds', this.choice.map(item => item.id).join(','))
              deletebatchcompany(formData).then(data => {
                console.log(data);
                if (data.success) {
                  this.$message.success('删除成功')
                  this.getCompList();
                } else {
                  this.$message.error(`${data.msg}`);
                }
              });
            }
          }
        });
      }
    },
    // 刷新公司
    freshTime () {
      if (this.choice.length < 1) {
        this.$message.error('请选择需要刷新的公司!');
      } else {
        let formData = new FormData();
        formData.append('companyIds', this.choice.map(item => item.id).join(','))
        freshtime(formData).then(data => {
          console.log(data);
          if (data.success) {
            this.getCompList();
            this.$message.success('刷新成功');
            this.passwordVisible = false;
          } else {
            this.$message.error(`${data.msg}`);
            this.passwordVisible = false;
          }
        });
      }
    },
    // feat： 法人库信息 齐枭飞
    legalPerson (row) {
      this.$router.push({
        path: '/legalPerson',
        query: {
          name: row.name
        }
      });
    },
    handleClick (row) {
      /**
     * opeType 个人用户 1   企业用户 2   管理员用户 3 why 不知道 问后台
     */
      this.$router.push({ path: '/log', query: { userName: row.userName, opeType: 2 } });
    },
    // 修改企业
    alterInfo (row) {
      // this.$router.push({ path: '/enterpriseAlter', query: { id: row.id } });
      bus.$emit('openTags', { fullPath: `/enterpriseAlter?id=${row.id}`, meta: { title: row.name } })
    },
    // 查询
    searchStatus () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.form.page = 1;
          this.getCompList();
        }
      });
    },
    // 审批
    onSubmit () {
      this.$refs.examine.validate(valid => {
        if (valid) {
          let query = {
            authType: this.examine.authType,
            auditCause: this.examine.auditCause,
            auditStatus: this.examine.auditStatus,
          }
          query.ids = this.choice.map(item => item.id).join(',');
          console.log(this.examine);
          (this.examine.authType === '1' ? companyAuthAll(query) : this.examine.authType === '2' ? companyStaffAuthAll(query) : companySsAuthAll(query)).then(data => {
            console.log(data);
            if (data.success) {
              this.$message.success(`审批完成`);
              this.getCompList();
            } else {
              this.$message.error(`${data.msg}`);
            }
            this.$refs.examine.resetFields();
            this.dialogVisible = false;
          });
        }
      });
    },
    examineClose () {
      this.$refs.examine.resetFields();
      this.dialogVisible = false;
    },
    handleSizeChange (val) {
      this.form.size = val;
      this.getCompList();
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange (val) {
      this.form.page = val;
      this.getCompList();
      console.log(`当前页: ${val}`);
    },
    // 单个认证跳转
    singleExamine (index, row) {
      let href = this.$router.resolve({ path: '/authInfo', query: { index, id: row.id } });
      window.open(href.href, '_blank');
    }
  }
};
</script>

<style scoped>
.container {
    /* width: 100%;
    height: 100%; */
    background: #ffffff;
}
.el-form {
    display: flex;
    align-items: center;
    justify-content: space-between;
}
.el-form .create_time {
    width: 212px !important;
}
.el-form .create_time /deep/ .el-date-editor {
    width: 144px;
}
.el-form .create_time /deep/ .el-date-editor /deep/ .el-input__inner {
    width: 144px;
}
.el-form .create_time /deep/ .el-form-item__content {
    display: inline-block;
}
.examine .el-form .el-form-item /deep/ .el-form-item__error {
    left: 150px;
}
.title div .el-form-item {
    width: 140px;
    display: inline-block;
    margin-right: 20px;
}
.el-form div.account {
    width: 250px;
}
.el-form .el-date-editor /deep/ .el-input__inner {
    width: 140px;
}
.el-form .btn_box {
    width: 180px;
}
.el-form .btn_box .el-button {
    width: 85px;
}
.el-table {
    /* height: 82%; */
}
.el-table /deep/ td,
.el-table /deep/ th {
    text-align: center;
}
.auth_box {
    margin-bottom: 20px;
    text-align: right;
}
.auth_box .el-button {
    width: 100px;
}
.auth_span {
    margin-right: 4px;
}
.page {
    width: 100%;
    height: 40px;
    background: #ffffff;
    text-align: center;
    padding-top: 20px;
}
.companyList /deep/ .el-table__body-wrapper {
    /* height: 655px; */
}
.el-dialog .el-form {
    flex: unset;
    display: block;
}
.el-dialog .el-form .el-form-item {
    display: block;
    margin-bottom: 20px;
}
.el-dialog .el-form /deep/ .el-form-item__label {
    width: 150px;
}
.el-dialog .el-form /deep/ .el-textarea {
    position: unset;
    width: 300px;
    height: 100px;
}
.el-dialog .el-form /deep/ .el-textarea textarea {
    width: 300px;
    height: 100px;
}
.el-dialog .el-form /deep/ .el-button {
    width: 100px;
    margin-right: 20px;
}
.el-dialog .mid_box {
    text-align: center;
}
.resetPassword .el-form-item {
    text-align: center;
}
.resetPassword .el-form .el-form-item .el-button {
    margin: 0 10px;
    width: 120px;
    height: 40px;
}
.resetPassword /deep/ .el-input__inner {
    height: 40px;
}
.resetPassword .el-dialog .el-form .el-form-item .el-form-item__content /deep/ .el-form-item__error {
    left: 0 !important;
}
.recommend .el-input {
    width: 100%;
}
.recommend .el-button {
    width: 100px;
}
.recommend /deep/ .el-input input.el-input__inner {
    width: 100%;
}
.page /deep/ .el-pagination .el-pagination__total {
    display: none;
}
.page /deep/ .el-pager li:last-child {
    display: none;
}
</style>